package su.mvc.service;


import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailService extends DaoSupport{
    
    public static final String TEMPLATE_PATH = "/WEB-INF/mailtemplates/";
    public static final String FULL_TEMPLATE_PATH = new File("").getAbsolutePath() + TEMPLATE_PATH;
    public static final String TEMPLATE_EXTENSION = ".txt";

    private static final Logger LOG = Logger.getLogger(MailService.class.getName());
    
    private String toEmail;
    
    private String toName;
    
    private String fromEmail;

    private String fromName;
    
    public void sendMail(String senderEmail, String senderName, String subj, String template, Map<String, String> templateProps){
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        
        templateProps.put("sender.name", senderName);
        templateProps.put("sender.mail", senderEmail);
        templateProps = completeTemplateProps(templateProps);

        String msgBody = getTemplate(template, templateProps);

        try {
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(fromEmail, fromName));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(toEmail, toName));
            msg.setReplyTo(new InternetAddress[]{new InternetAddress(senderEmail, senderName)});
            msg.setSubject(subj, "utf-8");
            msg.setText(msgBody);
            LOG.info(msgBody);
            Transport.send(msg);

        } catch (Exception e) {
            LOG.log(Level.SEVERE,"Error sending email from " + senderEmail, e);
        }
    }

    public String getTemplate(String textFile, Map<String, String> props) {
        textFile = FULL_TEMPLATE_PATH + textFile + TEMPLATE_EXTENSION;


        String template = null;
        File file = new File(textFile);
        try {
            template = readFile(file);
        } catch (IOException e) {
            LOG.log(Level.SEVERE, "Error reading email template file: " +textFile, e);
        }
        if (template == null || props == null) return template;
        for (String key: props.keySet()){
            if (!StringUtils.isEmpty(props.get(key))) {
                template = template.replaceAll("@" + key + "@", props.get(key));
            }
        }


        return template;

    }


    private String readFile(File file) throws IOException{
        StringBuilder builder = new StringBuilder();

        FileInputStream countriesF = new FileInputStream(file);
        BufferedReader br = new BufferedReader(new InputStreamReader(countriesF));
        String line = null;
        while((line = br.readLine()) != null) {
            builder.append(line);
            builder.append("\n");
        }
        return builder.toString();
    }
    
    private Map<String, String> completeTemplateProps(Map<String, String> props) {
        props.put("to.mail", toEmail);
        props.put("to.name", toName);
        props.put("from.mail", fromEmail);
        props.put("from.name", fromName);
        return props;
    }

    public String getToEmail() {
        return toEmail;
    }

    public void setToEmail(String toEmail) {
        this.toEmail = toEmail;
    }

    public String getToName() {
        return toName;
    }

    public void setToName(String toName) {
        this.toName = toName;
    }

    public String getFromEmail() {
        return fromEmail;
    }

    public void setFromEmail(String fromEmail) {
        this.fromEmail = fromEmail;
    }

    public String getFromName() {
        return fromName;
    }

    public void setFromName(String fromName) {
        this.fromName = fromName;
    }
}
